package com.ocom.mqzhongyu.business;

import com.ocom.mqzhongyu.feign.AccessClientService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.util.Map;


@Component
public class ConsumerMqListener {

	private Logger logger = LoggerFactory.getLogger(ConsumerMqListener.class);


	@Autowired
	private AccessClientService accessClientService;

	/**
	 * 把该监听命名为A监听
	 * 监听队列  远程服务支付接口发送消息  该队列会接受
	 * [message, headers, channel]
	 * @return {@link }
	 * @throws
	 */
	@RabbitListener(queues = "order_goods_stock_queue")
//	@RabbitListener(bindings = {
//			@QueueBinding(exchange = @Exchange(name = "order_goods_stock_exchange", type = "topic"),
//					value = @Queue(value = "order_goods_stock_queue"), key = {"routingKeys"})
//	})
	public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {

		// 手动签收消息,通知mq服务器端删除该消息
		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

		/** 注释
		 * 2023年2月2日11:16:17

		System.out.println("order_goods_stock_queue 消费中");
		System.out.println(message);
		String orderId = new String(message.getBody(), "UTF-8");

		//        设置限流策略
		//        channel.basicQos(获取消息最大数[0-无限制], 依次获取数量, 作用域[true作用于整个channel，false作用于具体消费者]);
	//TODO 数据库操作样例
		System.out.println("orderId-start:"+orderId);
		System.out.println(System.currentTimeMillis());

		try {
			JSONObject jsonObject=JSONObject.parseObject(orderId);

			Result result=accessClientService.getZyResult(jsonObject.getLong("companyId"),jsonObject.getString("identity"),jsonObject.getString("name"));
			//消费太快了  继续消费
			if(result.getCode()==4009){
				logger.info("中育-消费 异常-继续消费 【{}】", result);
				channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);//继续消费该消息
			}else{
				if(result.getCode()!=200 && result.getCode()!=4002 && result.getCode()!=4005) {
					logger.info("中育-消费 异常 【{}】", result);
				}
				// 手动签收消息,通知mq服务器端删除该消息
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
			}
//			需要处理重复消费，这里就不说明了
//			int a = 1/0;//模拟异常
//			if (true) {
//				System.out.println("手动签收消息,通知mq服务器端删除该消息");
//				// 手动签收消息,通知mq服务器端删除该消息
//				//channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("出现异常后，原本队列消息进入死信队列");
			logger.error("消息处理失败",orderId);
			//出现异常后，原本队列消息进入死信队列
//			channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
		}

		System.out.println("orderId-end"+orderId);
		System.out.println(System.currentTimeMillis());
		 */
	}

	/**
	 * 把该监听命名为B监听
	 * 监听死信队列  远程服务支付接口发送消息  该队列会接受
	 * [message, headers, channel]
	 * @return {@link }
	 * @throws
	 */
	@RabbitListener(queues = "order_goods_stock_die_queue")
	public void processForDie(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		//死信队列放弃
		channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);

//		String orderId = new String(message.getBody(), "UTF-8");
//
//		System.out.println("die:"+orderId);
//		//TODO 数据库操作样例
//
//		try {
//			int a = 1/0; //模拟死信队列出现异常
//			int cutNum = 0;//再次扣减库存
//			if (cutNum > 0) {
//				// 手动签收消息,通知mq服务器端删除该消息
//				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//			}
//
//		} catch (Exception e) {
//			e.printStackTrace();
//			//死信队列出现异常进入业务补偿机制
////			int orderNum = orderService.update(orderModel);
//			int orderNum = 0;
//			//TODO 数据库操作样例
//			//业务补偿
//			if(orderNum == 0){
//				// // 丢弃该消息
//				System.out.println("丢弃消息");
//				channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
//			}else {
//				channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);//继续消费该消息
//			}
//		}
	}

}
